package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import com.itheima.entity.Result;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @author Administrator
 * @version v1.0
 * @date 2019/10/13 21:15
 * @description TODO
 **/
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    public static final Logger log = Logger.getLogger(ValidateCodeController.class);

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        //半段手机号在五分钟内是否发送过了验证码
        String codeInRedis=jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (codeInRedis != null) {
            //已经发送过了
            return Result.error("验证码已发送，请注意查收");
        }

        //生成4位数验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (ClientException e) {
            log.error("Code send error.",e);
            return Result.error(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("发送的验证码为："+code);
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 5 * 60, code.toString());
        return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }


    @RequestMapping("/loginCode")
    public Result loginCode(String telephone) {
        //判断该手机号五分钟内是否收到过验证码
        String codeInRedis=jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (codeInRedis != null) {
            //已经发送过验证码了
            return Result.error("验证码已发送，请注意查收");
        }
        //生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);

        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
        } catch (ClientException e) {
            log.error("Code send error.",e);
            return Result.error(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("发送的验证码为："+code);
        jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 5 * 60, code.toString());
        return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}